package team.fourth.combat.web;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import team.fourth.combat.commen.constant.RedisConstant;
import team.fourth.combat.commen.entity.Result;
import team.fourth.combat.commen.utils.RedisUtil;
import team.fourth.combat.commen.utils.SignatureUtil;
import team.fourth.combat.pojo.Order;
import team.fourth.combat.pojo.OrderInfoVo;
import team.fourth.combat.service.OrderService;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    RedisUtil redisUtil;

    @Reference
    OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo){
        /**String token = orderInfoVo.getToken();
        if(token == null){
            return Result.error("无效请求");
        }

        Long count = redisUtil.delete(token);//redis 单线程（所有的请求来了都要排队）
        if(count == 0){
            return Result.error("无效请求");
        }*/


        String sign = SignatureUtil.sign(orderInfoVo);

        Long setnx = redisUtil.setnx(sign, sign);
        if(setnx == 0L){//setnx=1 说明设置成功
            return Result.error("无效请求 setnx");
        }

        String validateCode = orderInfoVo.getValidateCode();
        String telephone = orderInfoVo.getTelephone();
        //1、校验验证码
        String redisCode = redisUtil.get(telephone+ RedisConstant.SENDTYPE_ORDER);

        if(redisCode == null || !redisCode.equals(validateCode)){
            return Result.error("验证错误");
        }

        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);

        //2、调用预约服务下单
        Result result = orderService.submit(orderInfoVo);
        if(result.isFlag()){
            //3、下单成功给个提示（发送短信提示）
        }

        return result;
    }

    public static void main(String[] args) {
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setName("112");
        orderInfoVo.setSetmealId(5);
        String sign = SignatureUtil.sign(orderInfoVo);
        System.out.println(sign);
        //4cce8323b7665242595d2719b9d24a44
        //4cce8323b7665242595d2719b9d24a44

    }
}
